package Demo23;


import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class AdminDao extends Admin {
    private Connection conn;
    public AdminDao() throws ClassNotFoundException, SQLException, IOException{
        conn=SqlHelper.getConn();
    }

    public List<Cls> findAl() throws SQLException {
        String sql="select * from cls";
        List<Cls> list=new ArrayList<Cls>();
        PreparedStatement pState=conn.prepareStatement(sql);
        ResultSet rs=pState.executeQuery();
        while(rs.next()){
            Cls cls=new Cls();
            cls.setClsId(rs.getString("clsId"));
            cls.setClsName(rs.getString("clsName"));
            cls.setClsAdmin(rs.getString("clsAdmin"));
            cls.setClsTime(rs.getDate("clsTime"));
            list.add(cls);
        }
        return list;
    }

    //添加
    public void add(Admin admin) throws SQLException{
        String sql="insert into admin values(?,?)";
        PreparedStatement pstate=conn.prepareStatement(sql);
        pstate.setString(1, admin.getAdminId());
        Md5PasswordEncoder md5=new Md5PasswordEncoder();
        String pwd=md5.encodePassword(admin.getAdminPwd(), 1);
        pstate.setString(2, pwd);
        pstate.executeUpdate();
    }
    //删除
    public void del(String adminId) throws SQLException{
        String sql="delete from admin where adminId=?";
        PreparedStatement pstate=conn.prepareStatement(sql);
        pstate.setString(1, adminId);
        pstate.executeUpdate();
    }
    //修改
    public void update(Admin admin) throws SQLException{
        String sql="update admin set adminPwd=? where adminId=?";
        PreparedStatement pState=conn.prepareStatement(sql);
        pState.setString(1, admin.getAdminPwd());
        pState.setString(2, admin.getAdminId());
        pState.executeUpdate();
    }
    //查询
    public Admin findById(String adminId) throws SQLException{
        String sql="select * from admin where adminId=?";
        PreparedStatement pState=conn.prepareStatement(sql);
        pState.setString(1,adminId);
        ResultSet rs=pState.executeQuery();
        Admin admin=null;
        if(rs.next()){
            admin=new Admin();
            admin.setAdminId(rs.getString("adminId"));
            admin.setAdminPwd(rs.getString("adminPwd"));
        }
        return admin;
    }


    //查询所有记录
    public List<Admin> findAll() throws SQLException{
        String sql="select * from admin";
        List<Admin> list=new ArrayList<Admin>();
        Statement state=conn.createStatement();
        ResultSet rs=state.executeQuery(sql);
        while(rs.next()){
            Admin admin=new Admin();
            admin.setAdminId(rs.getString("adminId"));
            admin.setAdminPwd(rs.getString("adminPwd"));
            list.add(admin);
        }
        return list;
    }
}
